package com.verisette.ncos.service.master.bizunit;

import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Required;

import org.corp.agi.common.exception.ProcessException;
import org.corp.agi.service.bean.ProcessContext;
import org.corp.agi.service.bean.UserBean;
import org.corp.agi.service.bizunit.CommonBusinessUnit;
import org.corp.common.util.security.Encrypter;
import com.verisette.ncos.common.ProjectConstant;
import com.verisette.ncos.persistence.dao.UserProfileManagementDAO;
import com.verisette.ncos.persistence.domain.MasterUserProfile;

public class ResetUserPasswordBU extends CommonBusinessUnit {
	
	private Logger logger = Logger.getLogger(ResetUserPasswordBU.class);

	private Encrypter encrypter;
	@Autowired
	@Required
	public void setEncrypter(@Qualifier("encrypter")Encrypter encrypter) {
		this.encrypter = encrypter;
	}
	
	private UserProfileManagementDAO userProfileManagementDAO;
	@Required
	@Autowired
	public void setUserProfileManagementDAO(
			UserProfileManagementDAO userProfileManagementDAO) {
		this.userProfileManagementDAO = userProfileManagementDAO;
	}


	@Override
	public void execute(ProcessContext processContext) throws ProcessException {
		
		if(logger.isInfoEnabled()) logger.info( this.getClass().getSimpleName() + ": execute" );
		
		Map<String, Object> inputMap = (Map<String, Object>)processContext.getValueObject();
		MasterUserProfile userProfile = (MasterUserProfile)inputMap.get(ProjectConstant.USER_PROFILE);
		
		String defaultPassword = ProjectConstant.DEFAULT_PASSWORD;
		String encryptPassword = null;
		UserBean user = processContext.getUserBean();
		Date currentDate = new Date();
		
		try{
				if(defaultPassword != null && !"".equals(defaultPassword))
					encryptPassword = encrypter.encrypt(defaultPassword);
			
		}catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
		// Update UserResetPassword into MASTER_USER_PROFILE
		logger.debug("Update UserResetPassword into MASTER_USER_PROFILE.");
		
		userProfile.setUspPassword(encryptPassword); 
		userProfile.setUspForceChngPwdFlag(ProjectConstant.Y_FLAG);
		userProfile.setUspExpireDate(null);
		short s = 0;
		userProfile.setUspWrongLoginCounter(s);
		userProfile.setUspLockFlag(ProjectConstant.N_FLAG);
		
		userProfileManagementDAO.updateUserResetPassword(userProfile, user.getUsername(), currentDate);
		
		
	}

}
